# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponseRedirect
from SkyWalkingWeb import settings
from .models import Users
from proxy.views import proxy_view
from django.contrib.auth import login as d_login
import requests
import json
# Create your views here.


data = {
    "id": settings.id,
    "appid": settings.corpid,
    "agentid": settings.agentid,
    "redirect_uri": settings.redirect_uri,
    "state": settings.state
}

def index(request, prm):
    # 检查该用户是否登录
    print(request.path)
    print(prm)
    if request.user and request.user.is_authenticated:
        url = settings.oap_server_url + request.path
        return proxy_view(request, url)
    return render(request, 'login.html', {'Dict': json.dumps(data)})


def login(request):
    """登录页面"""
    # 检查该用户是否登录
    if request.user and request.user.is_authenticated:
        return proxy_view(request, settings.oap_server_url)
    return render(request, 'login.html', {'Dict': json.dumps(data)})


def wechat_login(request):
    """企业微信扫描登录"""
    wechat_id = None
    wechat_email = None
    wechat_name = None
    if request.method == 'GET':
        try:
            code = request.GET.get("code")
            url = requests.get(
                "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" %
                (settings.corpid, settings.corpsecret))
            access_token = url.json()['access_token']
            res = requests.get(
                "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s" %
                (access_token, code))
            wechat_id = res.json()['UserId']
            wechat_user = requests.get(
                "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s" %
                (access_token, wechat_id))
            wechat_name = wechat_user.json()['name']
            wechat_email = wechat_user.json()['email']
            print("code: %s" % code)
            print("access_token: %s" % access_token)
            print("wechat_id: %s" % wechat_id)
            print("wechat_email: %s" % wechat_email)
        except Exception as e:
            print('Scan fail, Exception: %s' % e)

    user = Users.objects.filter(wechat_id=wechat_id)
    # 检查该企业用户是否已有账号
    if user:
        if user[0].is_active:
            result = {'status': 0, 'msg': 'ok', 'data': None}
        else:
            result = {'status': 1, 'msg': '该用户已禁用', 'data': None}
    else:
        # 若无账号，新增用户数据，并初始化用户权限
        obj = Users(
            username=wechat_id.lower(),
            email=wechat_email,
            is_staff=0,
            is_active=1,
            display=wechat_name,
            wechat_id=wechat_id)
        obj.save()
        user = Users.objects.filter(wechat_id=wechat_id)
        result = {'status': 0, 'msg': 'ok', 'data': None}
    print(result)
    # 登陆跳转
    if result['status'] == 0:
        user = user[0]
        # 忽略密码认证的登录方式，用户登陆
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        d_login(request, user)
        # return proxy_view(request, settings.oap_server_url)
        return HttpResponseRedirect('/')
